package org.caowei.samples.web;

import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.HttpSession;

import org.caowei.samples.sevice.UserService;
import org.caowei.samples.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class LoginController {

	@Autowired
	private UserService UserService;

	// 进入登录页面
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String toLogin() {
		return "login/login";
	}

	// 进入登录
	// value object
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String doLogin(RedirectAttributes redirectAttributes,UserVO vo, HttpSession session) throws Exception {
		if (vo != null) {
			UserVO resultVO = UserService.getloginById(vo.getUserId());
			if (resultVO != null) {
				if (vo.getPassword() != null) {
					String encodePassword = vo.getPassword();
					Date currentTime = null;
					Calendar currentTimecalendar = Calendar.getInstance(); // 创建日历对象
					currentTimecalendar.setTime(new Date()); // 初始化时间 new Date()
																// -> 46
					currentTimecalendar.add(Calendar.MINUTE, -5); // 减5分 //41
					currentTime = currentTimecalendar.getTime(); // currentTime
																	// -> 41
					System.out.println(currentTime + "-----------------" + new Date());
					if (resultVO.getLastLockTime().before(currentTime)) {
						// 不在锁定时间范围内
						System.out.println("不在锁定时间范围内");
						if (encodePassword.equals(resultVO.getPassword())) {
							// 登录成功时清零
							resultVO.setLoginFailCount(0);
							UserService.updateUserLoginFailCout(resultVO);
							session.setAttribute("User", resultVO);
							return "redirect:/index";
						} else {
							resultVO.setLoginFailCount(resultVO.getLoginFailCount() + 1);
							if (resultVO.getLoginFailCount() == 3) {
								resultVO.setLoginFailCount(0);
								resultVO.setLastLockTime(new Date());
								UserService.updateUserLastLockTime(resultVO);
								redirectAttributes.addFlashAttribute("message","用户名或密码不能为空");
							}
							UserService.updateUserLoginFailCout(resultVO);
							redirectAttributes.addFlashAttribute("message","用户名或密码错误");
							return "redirect:/login";
						}
					} else {
						// 锁定时间范围内
						System.out.println("目前账号被锁定，无法登录，请稍等5分钟。");
						redirectAttributes.addFlashAttribute("message","目前账号被锁定，无法登录，请稍等5分钟。");
					}
				}
			}
		}
		return "login/login";
	}
	
//	@RequestMapping(value = "logout")
//	public String logout(HttpSession session){
//		session.removeAttribute("User");
//		return null;
//	}

}
